package com.igirl.manage.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.igirl.common.bean.PicUploadResult;
import com.igirl.manage.service.content.PropertiesService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @Author: jiaheng
 * @Description:
 * @Date: Created in 10:09 2017/12/23
 * @Modified:
 */

@Controller
@RequestMapping("pic")
public class PicUploadController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PicUploadController.class);

    /**
     * 加载资源类
     */
    @Autowired
    private PropertiesService propertiesService;

    /**
     * JacksonJson中的序列号工具
     */
    private static final ObjectMapper mapper = new ObjectMapper();

    private static final String[] IMAGE_TYPE = {".bmp",".jpg",".jpeg",".gif",".png"};

    @RequestMapping(value = "upload",method = RequestMethod.POST,produces = MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody
    public String upload(@RequestParam("uploadFile") MultipartFile uploadFile) throws IOException {
        //返回对象
        PicUploadResult result = new PicUploadResult();
        //校验图片格式
        boolean isLegal = false;
        //判断文件名是否合法
        for (String type : IMAGE_TYPE) {
            if (uploadFile.getOriginalFilename().endsWith(type)) {
                isLegal = true;
            }
        }
        if (!isLegal) {
            result.setError(1);
            return mapper.writeValueAsString(result);
        }
        //文件新路径
        String filePath = getFilePath(uploadFile.getOriginalFilename());
        //生成图片的绝对地址url
        String picUrl = StringUtils.substringAfterLast(filePath, "G:\\test\\igirl-upload").replace("\\", "/");
        result.setUrl(propertiesService.IMAGE_BASE_URL+picUrl);
        //写文件到磁盘里
        File newFile = new File(filePath);
        uploadFile.transferTo(newFile);
        //校验图片是否合法
        isLegal = false;
        try {
            BufferedImage image = ImageIO.read(newFile);
            if (image != null) {
                result.setWidth(image.getWidth()+"");
                result.setHeight(image.getHeight()+"");
                isLegal = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置返回状态
        result.setError(isLegal ? 0 : 1);
        //将返回结果对象转为JSON字符串返回
        return mapper.writeValueAsString(result);
    }

    public String getFilePath(String sourceFileName) {
        String baseFolder = propertiesService.IMAGE_REPOSITORY_PATH + File.separator + "images";
        Date nowDate = new Date();
        // 根据年月日：生成yyyy/MM/dd的目录结构
        String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy" + File.separator + "MM" + File.separator + "dd" );
        File file = new File(fileFolder);
        // 如果目录不存在，则创建目录
        if (!file.exists()) {
            file.mkdirs();
        }
        // 生成新的文件名
        String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
                + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
        // 返回文件的全路径
        return fileFolder + File.separator + fileName;
    }

    public static void main(String[] args) {
        String filePath = "D:\\test\\taotao-upload\\images\\2017\\12\\23\\2017122311244734907548.txt";
        String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, "D:\\test\\taotao-upload"), "\\", "/");
        System.out.println("picUrl = " + picUrl);
    }

}
